﻿namespace S4sme.Tasks.Blog
{
    using System;
    using System.Linq;

    using S4sme.Core.Extensions;
    using S4sme.Domain;
    using S4sme.Tasks.Blog.ViewModels;

    using SharpLite.Domain.DataInterfaces;

    /// <summary>
    /// Create - Update - Delete tasks for Posts
    /// </summary>
    public class PostCudTasks : BaseEntityCudTasks<Post, EditPostViewModel>
    {
        private readonly IRepository<Category> categoryRepository;

        private readonly IRepository<Tag> tagRepository;

        public PostCudTasks(IRepository<Post> postRepository, IRepository<Category> categoryRepository, IRepository<Tag> tagRepository)
            : base(postRepository)
        {
            this.categoryRepository = categoryRepository;
            this.tagRepository = tagRepository;
        }

        /// <summary>
        /// We only need to replace the basic CreateEditViewModel method in order to add categories
        /// to the view model which will be used to populate a drop down list.
        /// </summary>
        /// <returns>
        /// The create edit view model.
        /// </returns>
        public override EditPostViewModel CreateEditViewModel()
        {
            var viewModel = base.CreateEditViewModel();

            // These will be displayed by the view to select one or more product-category relationships
            viewModel.AvailableCategories = this.categoryRepository.GetAll().OrderBy(c => c.Name);
            viewModel.AvailableTags = this.tagRepository.GetAll().OrderBy(t => t.Name);

            return viewModel;
        }

        protected override void TransferFormValuesTo(Post toUpdate, Post fromForm)
        {
            toUpdate.Title = fromForm.Title;
            toUpdate.Description = fromForm.Description;
            toUpdate.Content = fromForm.Content;
            toUpdate.Slug = fromForm.Title.GenerateSlug();
            toUpdate.ModifiedDate = DateTime.Now; 
            
            toUpdate.Categories.Clear();

            foreach (var category in fromForm.Categories)
            {
                toUpdate.Categories.Add(category);
            }

            toUpdate.Tags.Clear();

            foreach (var tag in fromForm.Tags)
            {
                toUpdate.Tags.Add(tag);
            }
        }
    }
}
